package com.example.intelglasses;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.sunflower.FlowerCollector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	static boolean isConnecting = false; 	//判断按钮是处于"连接"还是"断开"
	private char connectFlag = 0;				//判断是否已经连接
	static Boolean isch1able = false;		//判断CH1按钮是处于"开"还是"关"
	static Boolean isch2able = false;		//判断CH2按钮是处于"开"还是"关"
	static Boolean isch3able = false;		//判断CH1+2按钮是处于"开"还是"关"
	static float mutinum = 2f;					//波形整体缩放倍率
	static int circleSize;							//圆圈的大小
	static float addOrSub=-190f;				//波形抬高值
	static boolean flagactChange = false; //判断是否是是从别activity跳来的
	int screenwidth;									//手机的分辨率宽度,用于适配不同分辨率的手机
	static float paintscale = 1.0f;				//根据分辨率改变这个scale值
	String ch1max, ch1min, ch1cha, ch2max, ch2min, ch2cha, ch1fhz, ch2fhz, //各种电气参数,用于参数更新
			axisX, axisY;
	static int maxch1, maxch2, minch1, minch2, passvalue1, passvalue2;		//用于电气参数的计算
	static String ipstring;							//ipstring用于intent的带参切换
	static int portInt;								//portInt用于intent的带参切换
	static float valueRaiseVolt = 1.6f;		//用于调整电气参数

	private EditText IPText;				//IP的编辑栏
	private TextView statusText;		//左上角状态信息
	private TextView multiText;		//波形整体缩放倍率的数值显示
	private TextView textX;				//显示X轴单格表示的ms数
	private TextView textY;				//显示Y轴单格表示的V数
	private Button buttch1;				//CH1开关按钮
	private Button buttch2;				//CH2开关按钮
	private Button buttch3;				//CH1+2开关按钮
	private Button buttadd;				//波形抬高按钮
	private Button buttsub;				//波形抬低按钮
	private Button buttchange;		//切换到信号发生器的按钮
	private Button buttchange2;  	//切换到数据查询的按钮
	private Button startButton;		//开始连接的按钮
	private ImageButton buttsave;  //保存记录的按钮
	private Button buttSeekBar;		//发送数值拉条按钮
	private SeekBar seebar1;			//DIV的数值拉条
	
	public SQLiteDatabase dbmain;		//数据库
	
	private Thread mThreadClient = null;
	private Socket mSocketClient = null;
	static BufferedReader mBufferedReaderServer = null;
	static PrintWriter mPrintWriterServer = null;
	static BufferedReader mBufferedReaderClient = null;
	static PrintWriter mPrintWriterClient = null;
	static InputStream myInputStream;
	private String recvMessageClient = "";
	static char[] buffferFromCH1 = new char[101]; // CH1的数据接收buffer
	static char[] bufferFromCH2 = new char[101]; // CH2的数据接收buffer
	char[] buffer1;												//socket接到的数据临时存放在这里

	private Vibrator vibrator;	 //震动
	public MyView view1;		//绘图的类

	private ImageButton buttvoiceButton;		//触发语音识别
	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog mIatDialog;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	private Toast mToast;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;
	// printResult会发神经执行2次,所以立下flag砍掉1次
	private boolean firstFlag = true;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);	//全屏但没有去bar
		startButton = (Button) findViewById(R.id.startButt);
		IPText = (EditText) findViewById(R.id.editTextIPINPUT);
		statusText = (TextView) findViewById(R.id.textStatus);
		multiText = (TextView) findViewById(R.id.textmulti);
		textX = (TextView) findViewById(R.id.textX);
		textY = (TextView) findViewById(R.id.textY);
		view1 = (MyView) findViewById(R.id.canvaslayout);
		buttch1 = (Button) findViewById(R.id.ch1Butt);
		buttch2 = (Button) findViewById(R.id.ch2Butt);
		buttch3 = (Button) findViewById(R.id.ch3Butt);
		buttadd = (Button) findViewById(R.id.addButt);
		buttsub = (Button) findViewById(R.id.subButt);
		buttchange = (Button) findViewById(R.id.buttcontext1); // 信号发生器按钮
		buttchange2 = (Button) findViewById(R.id.buttcontext4);// 记录查询按钮
		buttsave = (ImageButton) findViewById(R.id.buttsave);
		buttvoiceButton = (ImageButton) findViewById(R.id.buttvoiceOSC);
		seebar1 = (SeekBar) findViewById(R.id.seekbarMain);
		buttSeekBar = (Button) findViewById(R.id.buttforSeekBarMain);

		// 初始化识别对象
		mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
		// 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
		mIatDialog = new RecognizerDialog(MainActivity.this, mInitListener);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mEngineType = SpeechConstant.TYPE_CLOUD;//在线识别

		//获取分辨率并改变scale值
		Display mdisplay = getWindowManager().getDefaultDisplay();
		screenwidth = mdisplay.getWidth();
		if (screenwidth == 720) {
			paintscale = 1.0f;
		}
		if (screenwidth == 1080) {
			paintscale = 1.5f;
		}
		//各电气参数的初始化
		ch1max = "00";
		ch1min = "00";
		ch1cha = "00";
		ch1fhz = "000";
		ch2max = "00";
		ch2min = "00";
		ch2cha = "00";
		ch2fhz = "000";
		axisX = "???";
		axisY = "???";
		IPText.setText("192.168.1.118:6000");
		IPText.setText("192.168.43.242:8000");
		//震动服务的初始化
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		long[] pattern = { 100, 60, 100, 60 };
		vibrator.vibrate(pattern, -1);
		//各种按钮的初始化
		isch2able = true;
		isch3able = true;
		buttch2.setText("CH2->开");
		buttch3.setText("CH1+2->开");
		// 拖动条的监听
		seebar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}
			@Override			//拉动seekbar则触发
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (seebar1.getProgress() == 0) {//防止0的出现,故拉到0自动切到1
					seebar1.setProgress(1);
				}//按钮的text随着Seekbar的值改变而改变
				buttSeekBar.setText(String.valueOf(seebar1.getProgress()));
			}
		});
		if (flagactChange == true) { //flagactChange静态参数切到别的activity时不会复位
			startButton.performClick();	//从别的activity切换过来能自动激活连接按钮
		}
	}

	/*****************************声控系列**************************************/
	/*******************************开始****************************************/
	/**初始化监听器 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败，错误码：" + code);
			}
		}
	};
	/**
	 * 听写监听器。
	 */
	private RecognizerListener recognizerListener = new RecognizerListener() {

		@Override
		public void onBeginOfSpeech() {
			showTip("开始说话");
		}

		@Override
		public void onError(SpeechError error) {
			// Tips：
			// 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
			// 如果使用本地功能（语音+）需要提示用户开启语音+的录音权限。
			showTip(error.getPlainDescription(true));
		}
		@Override
		public void onEndOfSpeech() {
			showTip("结束说话");
		}
		@Override
		public void onResult(RecognizerResult results, boolean isLast) {
			// printResult(results);
			if (isLast) {
			}
		}
		@Override
		public void onVolumeChanged(int volume) {
			showTip("当前正在说话，音量大小：" + volume);
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
		}
	};
	/**声控内容的判断主要在这里进行*/
	private void printResult(RecognizerResult results) {
		if (firstFlag == true) {
			firstFlag = false;
			String text = JsonParser.parseIatResult(results.getResultString());
			String sn = null;
			// 读取json结果中的sn字段
			try {
				JSONObject resultJson = new JSONObject(
						results.getResultString());
				sn = resultJson.optString("sn");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mIatResults.put(sn, text);

			StringBuffer resultBuffer = new StringBuffer();
			for (String key : mIatResults.keySet()) {
				resultBuffer.append(mIatResults.get(key));
			}
			switch (JudgeVoice.returnOSC(resultBuffer.toString())) {
			case 1:
				buttchange.performClick();
				break;
			case 2:
				buttchange2.performClick();
				break;
			case 10:
				startButton.performClick();
				break;
			case 11:
				this.finish();
				break;
			case 21:
				buttch1.performClick();
				break;
			case 22:
				buttch2.performClick();
				break;
			case 0:
				Toast.makeText(MainActivity.this, "识别不出来呀~~~",
						Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		} else {
			firstFlag = true;
		}
	}

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}
	};
	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}
	/**
	 * 参数设置
	 * @param param
	 * @return
	 */
	public void setParam() {
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);

		// 设置听写引擎
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		// 设置返回结果格式
		mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
		String lag = "zh_cn";
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}
		// 设置语音前端点
		mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
		// 设置语音后端点
		mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
		// 设置标点符号
		mIat.setParameter(SpeechConstant.ASR_PTT, "0");
		// 设置音频保存路径
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
				Environment.getExternalStorageDirectory()
						+ "/iflytek/wavaudio.pcm");
		// 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
		// 注：该参数暂时只对在线听写有效
		mIat.setParameter(SpeechConstant.ASR_DWA, "0");
	}

	@Override
	protected void onResume() {
		// 移动数据统计分析
		FlowerCollector.onResume(MainActivity.this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 移动数据统计分析
		FlowerCollector.onPause(MainActivity.this);
		super.onPause();
	}
	
	int ret = 0;
	/** 声控的按钮事件 */
	public void voiceActriveOSC(View sourve) {
		mIatResults.clear();
		setParam();
		boolean isShowDialog = true;
		if (isShowDialog) {
			// 显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			mIatDialog.show();
			showTip(getString(R.string.text_begin));
		} else {
			// 不显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			ret = mIat.startListening(recognizerListener);
			if (ret != ErrorCode.SUCCESS) {
				showTip("听写失败,错误码：" + ret);
			} else {
				showTip(getString(R.string.text_begin));
			}
		}
	}
	/*****************************声控系列**************************************/
	/*******************************结束****************************************/

	/** 保存数据到数据库的按键事件 */
	public void onclicksave(View sourve) {
		// 获取当前日期和时间
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy.MM.dd  HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String strdate = formatter.format(curDate);
		String strch1 = ch1max + ch1min + ch1cha + ch1fhz;
		String strch2 = ch2max + ch2min + ch2cha + ch2fhz;
		vibrator.vibrate(20);
		// 数据库的更新:update典型用法
		try {
			dbmain = SQLiteDatabase.openOrCreateDatabase("/sdcard/oscdata",
					null);
			dbmain.execSQL(
					"update mydata set ch1=? where date=(select min(date) from mydata)",
					new String[] { strch1 });
			dbmain.execSQL(
					"update mydata set ch2=? where date=(select min(date) from mydata)",
					new String[] { strch2 });
			dbmain.execSQL(
					"update mydata set buffer1=? where date=(select min(date) from mydata)",
					new String[] { String.valueOf(buffferFromCH1) });
			dbmain.execSQL(
					"update mydata set buffferFromCH1=? where date=(select min(date) from mydata)",
					new String[] { String.valueOf(bufferFromCH2) });
			dbmain.execSQL(
					"update mydata set date=? where date=(select min(date) from mydata)",
					new String[] { strdate });
			Toast.makeText(MainActivity.this, "采样值和波形记录成功!!", Toast.LENGTH_LONG)
					.show();
		} catch (Exception e) {
			Toast.makeText(MainActivity.this, "数据库更新失败", Toast.LENGTH_LONG)
					.show();
		}
		dbmain.close();
	}
	/**CH1按钮的按键事件*/
	public void clickedch1(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (isch1able == false) {
				isch1able = true;
				buttch1.setText("CH1->开");
				vibrator.vibrate(20); // 震动20ms
				view1.invalidate();	//绘图更新
				mPrintWriterClient.print("&+^");// 把里面的内容放入发送缓冲区
				mPrintWriterClient.flush(); // 发送缓冲区的东西
			} else {
				isch1able = false;
				buttch1.setText("CH1->关");
				vibrator.vibrate(20); // 震动20ms
				view1.invalidate();//绘图更新
				mPrintWriterClient.print("&(^");// 把里面的内容放入发送缓冲区
				mPrintWriterClient.flush(); // 发送缓冲区的东西
			}
		}
	}
	/**CH2按钮的按键事件*/
	public void clickedch2(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (isch2able == false) {
				isch2able = true;
				buttch2.setText("CH2->开");
				vibrator.vibrate(20); // 震动20ms
				view1.invalidate();//绘图更新
				mPrintWriterClient.print("&-^");// 把里面的内容放入发送缓冲区
				mPrintWriterClient.flush(); // 发送缓冲区的东西
			} else {
				isch2able = false;
				buttch2.setText("CH2->关");
				vibrator.vibrate(20); // 震动20ms
				view1.invalidate();//绘图更新
				mPrintWriterClient.print("&)^");// 把里面的内容放入发送缓冲区
				mPrintWriterClient.flush(); // 发送缓冲区的东西

			}
		}

	}
	/**CH1+2按钮的按键事件*/
	public void clickedch3(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (isch3able == false) {
				isch3able = true;
				buttch3.setText("CH1+2->开");
				view1.invalidate();//绘图更新
				vibrator.vibrate(20); // 震动20ms
			} else {
				isch3able = false;
				buttch3.setText("CH1+2->关");
				view1.invalidate();//绘图更新
				vibrator.vibrate(20); // 震动20ms
			}
		}
	}

	/** 波形整体升按钮 */
	public void clickedadd(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (addOrSub <= 400f) {
				addOrSub += 5f;
				view1.invalidate();//绘图更新
				vibrator.vibrate(10); // 震动20ms
			}
		}
	}

	/** 波形整体降按钮 */
	public void clickedsub(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (addOrSub >= (-700f)) {
				addOrSub -= 5f;
				view1.invalidate();
				vibrator.vibrate(10); // 震动20ms
			}
		}
	}

	/** 缩放按钮 + */
	public void clickedmulti1(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (mutinum <= 10f) {
				mutinum += 0.5f;
				view1.invalidate();//绘图更新
				updateString();	//电气参数更新
				vibrator.vibrate(10); // 震动20ms
				multiText.setText("  波形缩放倍率: " + String.valueOf(mutinum));
			}
		}
	}

	/** 缩放按钮 - */
	public void clickedmulti2(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			if (mutinum > 1f) {
				mutinum -= 0.5f;
				updateString();	//电气参数更新
				view1.invalidate();//绘图更新
				vibrator.vibrate(10); // 震动20ms
				multiText.setText("  波形缩放倍率: " + String.valueOf(mutinum));
			}
		}
	}

	/** DIV按钮 */
	public void clickleftBarMain(View sourve) {
		if (isConnecting == true && connectFlag == 1) {
			String tempProgressStr = String.valueOf(seebar1.getProgress());
			if (seebar1.getProgress() >= 10) {	//十位在前面添1个0
				mPrintWriterClient.print("&T0" + tempProgressStr + "^");
			} else {//个位在前面添2个0
				mPrintWriterClient.print("&T00" + tempProgressStr + "^");
			}
			mPrintWriterClient.flush(); // 发送缓冲区的东西
		}
	}

	/** 切换模式的按钮->信号发生器act */
	public void changtocontext(View sourve) {
		Intent intent = new Intent();
		intent.putExtra("ipstring", ipstring);		//将后面的string值绑定到前面的键值
		intent.putExtra("portint", String.valueOf(portInt));
		intent.setClass(MainActivity.this, generator.class);
		flagactChange = true;
		startActivity(intent);
		MainActivity.this.finish();
	}

	/** 切换模式的按钮 ->数据查询act */
	public void changtocontext4(View sourve) {
		Intent intent = new Intent();
		intent.putExtra("ipstring", ipstring);
		intent.putExtra("portint", String.valueOf(portInt));
		intent.setClass(MainActivity.this, QueryData.class);
		flagactChange = true;
		startActivity(intent);
		MainActivity.this.finish();
	}

	/** 开始连接按钮的事件 */
	public void clicked1(View sourve) {
		if (isConnecting) {
			isConnecting = false;
			try {
				if (mSocketClient != null) {// 关闭socket连接
					mSocketClient.close();
					mSocketClient = null;
					mPrintWriterClient.close();
					mPrintWriterClient = null;
				}
			} catch (IOException e) {
				e.printStackTrace(); // 深度的调试信息
			}
			mThreadClient.interrupt();
			startButton.setText("连接"); // "停止连接"按钮切换为"开始连接"
			statusText.setText("连接断开!");
			IPText.setEnabled(true);
			connectFlag = 0;
			vibrator.vibrate(10); // 震动20ms
		} else {
			isConnecting = true;
			startButton.setText("断开"); // "开始连接"按钮切换到"停止连接"
			IPText.setEnabled(false);
			mThreadClient = new Thread(mRunnable); // new出一个wifi线程
			mThreadClient.start(); // 开启线程
		}
	}

	private Runnable mRunnable = new Runnable() {
		public void run() {
			String msgText = IPText.getText().toString(); // 获取输入的IP地址
			if (msgText.length() == 0) {
				recvMessageClient = "IP为空!!!";// 消息
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
				return;
			}
			int start = msgText.indexOf(":"); // 返回一个字符在字符串的位置
			if ((start == -1) || (start + 1 >= msgText.length())) {
				recvMessageClient = "IP不合法!!!";// 消息
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
				return;
			}
			String sIP = msgText.substring(0, start); // 截取 >=0 且 <start位置 的字符串
			String sPort = msgText.substring(start + 1); // 截取 start+1位置及后面的字符串
			int port = Integer.parseInt(sPort); // String 转 int
			ipstring = sIP;
			portInt = port;

			Log.d("gjz", "IP:" + sIP + ":" + port);

			try {
				mSocketClient = new Socket(sIP, port); // Port_num
				mBufferedReaderClient = new BufferedReader(
						new InputStreamReader(mSocketClient.getInputStream()));
				// myInputStream=mSocketClient.getInputStream();
				// 绑定输入流
				mPrintWriterClient = new PrintWriter(
						mSocketClient.getOutputStream(), true);
				recvMessageClient = "连接成功!";// 消息
				connectFlag = 1; // 连接成功标志立起来
				vibrator.vibrate(50);
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				recvMessageClient = "IP 错误!!";// 消息
				connectFlag = 0; // 连接标志置0
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
				return;
			}
			buffer1 = new char[101];
			while (isConnecting) {
				try {
					mBufferedReaderClient.read(buffer1);
					if (buffer1[0] == '#') {
						Message msg = new Message();
						msg.what = 2;
						mHandler.sendMessage(msg);
					}
					if (buffer1[0] == '*') {
						Message msg = new Message();
						msg.what = 3;
						mHandler.sendMessage(msg);
					}
					if (buffer1[0] == '$') {
						Message msg = new Message();
						msg.what = 4;
						mHandler.sendMessage(msg);
					}

				} catch (IOException e) {
				}

			}
		}
	};
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
			} else if (msg.what == 1) {
				if (recvMessageClient == "IP为空!!!"
						|| recvMessageClient == "IP 错误!!") {
					vibrator.vibrate(400);
					startButton.performClick();
				} else if (recvMessageClient == "已连接成功!") {
				}
				statusText.setText(recvMessageClient); // 刷新消息
			} else if (msg.what == 2) { // 2表示收到'1'
				maxch1 = 0;
				minch1 = 255;
				//抽取出最大值和最小值分别保存到maxch1和minch1
				for (int j = 0; j <= 100; j++) {
					buffferFromCH1[j] = buffer1[j];
					if (j >= 1) {
						if (maxch1 <= (int) buffer1[j]) {
							maxch1 = (int) buffer1[j];
						}
						if (minch1 >= (int) buffer1[j]) {
							minch1 = (int) buffer1[j];
						}
					}
				}
				updateString();
				circleSize = 270;
				view1.invalidate();
			} else if (msg.what == 3) {
				maxch2 = 0;
				minch2 = 255;
				for (int j = 0; j <= 100; j++) {
					bufferFromCH2[j] = buffer1[j];
					if (j >= 1) {
						if (maxch2 <= (int) buffer1[j]) {
							maxch2 = (int) buffer1[j];
						}
						if (minch2 >= (int) buffer1[j]) {
							minch2 = (int) buffer1[j];
						}
					}
				}
				updateString();
				circleSize = 260;
				view1.invalidate();
			} else if (msg.what == 4) {
				buttvoiceButton.performClick();
			}
		}
	};

	/** 手动设置各种电气参数 */
	public void setstring(String per, String chMa, String chMi, String chcha,
			Boolean isX) {
		if (isX == true) {
			textX.setText("X轴每格:" + per + "  CH1最大:" + chMa + "  CH1最小:" + chMi
					+ "  CH1电压差值:" + chcha);
		} else {
			textY.setText("Y轴每格:" + per + "  CH2最大:" + chMa + "  CH2最小:" + chMi
					+ "  CH2电压差值:" + chcha);
		}
	}

	/** 计算和更新CH1和CH2的最大值最小值频率差值等等 */
	public void updateString() {
		axisX = "150";
		axisY = String.valueOf(((float) (Math
				.round(MainActivity.mutinum * 0.1 * 100)) / 100));
		int intervalue1 = (maxch1 + minch1) / 2;	//中间值1,作为二乘法的减数
		int intervalue2 = (maxch2 + minch2) / 2; //中间值2,作为二乘法的减数
		int firstpos1 = 99, secondpos1 = 0, firstpos2 = 99, secondpos2 = 0;
		boolean negflag1 = false, negflag2 = false;  //是否为负数的flag,true代表前面已经有2个点处于中间值
		//遍历buffer中的99个数，最后一个数不用比，不然溢出
		for (int arraynum = 0; arraynum < 99; arraynum++) {
			//如果前后两个数的乘积为负数且前面处于中间值的点小于2
			if ((((int) buffferFromCH1[arraynum] - intervalue1)
					* ((int) buffferFromCH1[arraynum + 1] - intervalue1) < 0)
					&& (!negflag1)) {
				if (firstpos1 > arraynum) {
					firstpos1 = arraynum;			//符合条件,保存第一个点
				} else {
					secondpos1 = arraynum;	//符合条件,保存第二个点
					negflag1 = true;				//2个点都已经采集完,flag立起来
				}
			}
			//上面是CH1的2个点的采集,下面是CH2的采集,道理一样
			if ((((int) bufferFromCH2[arraynum] - intervalue2)
					* ((int) bufferFromCH2[arraynum + 1] - intervalue2) < 0)
					&& (!negflag2)) {
				if (firstpos2 > arraynum) {
					firstpos2 = arraynum;
				} else {
					secondpos2 = arraynum;
					negflag2 = true;
				}
			}
		}
		//当输入信号为水平直线时,频率强制置0
		if (secondpos1 == 0) {
			ch1fhz = "0";
		} else {
			try {
				ch1fhz = String.valueOf(1000 / (secondpos1 - firstpos1));
			} catch (Exception e) {
				Toast.makeText(MainActivity.this, "除数不要为零", Toast.LENGTH_LONG)
						.show();
			}
		}
		if (secondpos2 == 0) {
			ch2fhz = "0";
		} else {
			try {
				ch2fhz = String.valueOf(1000 / (secondpos2 - firstpos2));
			} catch (Exception e) {
				Toast.makeText(MainActivity.this, "除数不要为零", Toast.LENGTH_LONG)
						.show();
			}
		}
		//根据前面计算出的firstpos和secondpos就可以算出周期进而得出频率
		float temp1 = ((float) Math
				.round((10 * 3.3f * (float) (maxch1 - 64)) / 128)) / 10;
		float temp2 = ((float) Math
				.round((10 * 3.3f * (float) (minch1 - 64)) / 128)) / 10;
		ch1max = String.valueOf(((float) Math
				.round((10 * 3.3f * (float) (maxch1 - 64)) / 128)) / 10);
		ch1min = String.valueOf(((float) Math
				.round((10 * (3.3f * (float) (minch1 - 64)) / 128))) / 10);
		ch1cha = String
				.valueOf((float) Math.round(((temp1 - temp2) * 10)) / 10);
		temp1 = ((float) Math.round((10 * 3.3f * (float) (maxch2 - 64)) / 128)) / 10;
		temp2 = ((float) Math.round((10 * 3.3f * (float) (minch2 - 64)) / 128)) / 10;
		ch2max = String.valueOf(((float) Math
				.round((10 * +3.3f * (float) (maxch2 - 64)) / 128)) / 10);
		ch2min = String.valueOf(((float) Math
				.round((10 * 3.3f * (float) (minch2 - 64) / 128))) / 10);
		ch2cha = String
				.valueOf((float) Math.round(((temp1 - temp2) * 10)) / 10);
		textX.setText("X轴每格:" + axisX + "us   CH1的频率:" + ch1fhz + "Hz\n"
				+ " CH1最大:" + ch1max + "V" + "  CH1最小:" + ch1min + "V"
				+ "  CH1电压差值:" + ch1cha + "V");
		textY.setText("Y轴每格:" + axisY + "V   CH2的频率:" + ch2fhz + "Hz\n"
				+ " CH2最大:" + ch2max + "V" + "  CH2最小:" + ch2min + "V"
				+ "  CH2电压差值:" + ch2cha + "V");
	}

	private String getInfoBuff(char[] buff, int count) {
		char[] temp = new char[count];
		for (int i = 0; i < count; i++) {
			temp[i] = buff[i];
		}
		return new String(temp);
	}

	public void onDestroy() {
		super.onDestroy();
		if (isConnecting) {
			isConnecting = false;
			try {
				if (mSocketClient != null) {
					mSocketClient.close();
					mSocketClient = null;
					mPrintWriterClient.close();
					mPrintWriterClient = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			mThreadClient.interrupt();
			connectFlag = 0;
		}
	}
}

/*********************************** 示波器绘图的类 *****************************************/
class MyView extends View {

	Path path1, path2, path3;
	public char flagfirst = 0;

	public MyView(Context context, AttributeSet set) {
		super(context, set);
		path1 = new Path();
		path2 = new Path();
		path3 = new Path();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (flagfirst != 2) {
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setColor(Color.WHITE);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(1);
			// 画网格
			for (int i1 = 0; i1 < 21; i1++) {
				canvas.drawLine(0, 0, 0, 540 * MainActivity.paintscale, paint);
				canvas.translate(30 * MainActivity.paintscale, 0);
			}
			canvas.translate(-630 * MainActivity.paintscale, 0);
			for (int i1 = 0; i1 < 19; i1++) {
				canvas.drawLine(0, 0, 600 * MainActivity.paintscale, 0, paint);
				canvas.translate(0, 30 * MainActivity.paintscale);
			}
			canvas.translate(0, -570 * MainActivity.paintscale);
			paint.setStrokeWidth(2);
			// 画圆圈
			canvas.drawCircle(300 * MainActivity.paintscale,
					270 * MainActivity.paintscale, MainActivity.circleSize
							* MainActivity.paintscale, paint);
			paint.setTextSize(30);
			// 画坐标
			canvas.drawText("0", 5 * MainActivity.paintscale,
					270 * MainActivity.paintscale, paint);
			paint.setStrokeWidth(4);
			// 画XY轴
			canvas.drawLine(0, 0, 0, 540 * MainActivity.paintscale, paint);
			canvas.drawLine(0, 270 * MainActivity.paintscale,
					600 * MainActivity.paintscale,
					270 * MainActivity.paintscale, paint);
			// 画Path1
			path1.moveTo(0, (float) ((float) (MainActivity.buffferFromCH1[1])
					* MainActivity.mutinum * (-1) * MainActivity.paintscale
					+ 270 * MainActivity.paintscale - MainActivity.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path1.lineTo(
						(float) ((i - 1) * 6 * MainActivity.paintscale),
						(float) ((MainActivity.buffferFromCH1[i])
								* MainActivity.mutinum * (-1)
								* MainActivity.paintscale + 270
								* MainActivity.paintscale - MainActivity.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.GREEN);
			if (MainActivity.isch1able == false) {
				canvas.drawPath(path1, paint);
			}
			path1.reset();
			// 画Path2
			path2.moveTo(0, (float) ((MainActivity.bufferFromCH2[1])
					* MainActivity.mutinum * (-1) * MainActivity.paintscale
					+ 270 * MainActivity.paintscale - MainActivity.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path2.lineTo(
						(float) ((i - 1) * 6 * MainActivity.paintscale),
						(float) ((MainActivity.bufferFromCH2[i])
								* MainActivity.mutinum * (-1)
								* MainActivity.paintscale + 270
								* MainActivity.paintscale - MainActivity.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.RED);
			if (MainActivity.isch2able == false) {
				canvas.drawPath(path2, paint);
			}
			path2.reset();
			// 画Path3
			path3.moveTo(
					0,
					(float) (((MainActivity.bufferFromCH2[1] + MainActivity.buffferFromCH1[1]))
							* MainActivity.mutinum
							* (-1)
							* MainActivity.paintscale
							+ 270
							* MainActivity.paintscale - MainActivity.addOrSub));
			for (int i = 2; i <= 100; i++) {
				path3.lineTo(
						(float) ((i - 1) * 6 * MainActivity.paintscale),
						(float) (((MainActivity.bufferFromCH2[i]) + (MainActivity.buffferFromCH1[i]))
								* MainActivity.mutinum
								* (-1)
								* MainActivity.paintscale
								+ 270
								* MainActivity.paintscale - MainActivity.addOrSub));
			}
			paint.setPathEffect(null);
			paint.setColor(Color.YELLOW);
			if (MainActivity.isch3able == false) {
				canvas.drawPath(path3, paint);
			}
			path3.reset();
		}
		flagfirst = 1;
	}
}